#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include "nvcappctl.h"

void print_help();
char process_cmd(char * cmd);
unsigned short get_listen_port();
void send_cmd(char cmd, char * arg);
int sockfd;
int main(int argc, char ** argv)
{
	char cmd, timeout;
	char msg[2];
	unsigned short port;

	timeout = 3;

	if(argc != 2 || (cmd = process_cmd(argv[1])) == -1)
		return -1;

	if((port = get_listen_port()) == 0)//default port = 3333
		port = 3333;

	printf("begin to %s the system ...\n", argv[1]);
	if((sockfd = get_socket("127.0.0.1", port)) > 0)//sub process is running
	{
		if(cmd == MSG_START)
			printf("system is running now, needn't to start!\n");
		else
			send_cmd(cmd, argv[1]);
		return 0;
	}
	if(cmd == MSG_STOP)
	{
		printf("system is not running, needn't to stop.\n");
		return 0;
	}
	if(!fork())//start sub process
	{
		run();
		exit(0);
	}
	while((sockfd = get_socket("127.0.0.1", port)) == -1 && timeout-- > 0)
	{
		sleep(1);
	}
	if(sockfd > 0)
	{
		send_cmd(cmd, argv[1]);
		/*if(cmd == MSG_START && recv(sockfd, msg, 2, 0) > 0)
		{
			if(msg[0] == MSG_START)
				printf("system start successful echo\n");
			if(msg[0] == MSG_STOP)
				printf("system echo failue\n");
			return msg[0] == MSG_START ? 0 : -1;
		}*/
	}
	else
		printf("can't %s system.\n", argv[1]);

	return 0;
}

unsigned short get_listen_port()
{
	FILE * filp;
	unsigned short port;
	struct nv_conn_config * conn_;

	if((filp = fopen("conn.conf","rt")) == NULL)
		return 0;
	if(read_conn_config(filp, &conn_))
	{
		fclose(filp);
		return 0;
	}
	fclose(filp);
	if(conn_ == NULL)
		return 0;

	port = get_socket_port("client", conn_);
	release_conn_config(conn_);
	return port;
}
void print_help()
{
	printf("Usage: nvc option\n");
	printf("       option : start - to start the system\n");
	printf("                stop  - to stop the system\n");
}

char process_cmd(char * cmd)
{
	if(strcasecmp(cmd, "start") == 0)
		return MSG_START;
	else if(strcasecmp(cmd, "stop") == 0)
		return MSG_STOP;
	else if(strcasecmp(cmd, "pause") == 0)
		return MSG_PAUSE;
	else if(strcasecmp(cmd, "resume") == 0)
		return MSG_RESUME;
	else
		printf("%s is not a valid command, please try again!\n", cmd);
	return -1;
}
void send_cmd(char cmd, char * arg)
{
	char msg[2];
	msg[0] = cmd;

	if(send(sockfd, msg, 1, 0) == -1)
		printf("sorry, can't %s the system.\n", arg);
	else
		printf("%s the system successfully.\n", arg);
	close(sockfd);
}